package com.stxx.framwork.config;

import com.alibaba.fastjson2.JSONWriter;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import org.noear.solon.serialization.fastjson2.Fastjson2ActionExecutor;
import org.noear.solon.serialization.fastjson2.Fastjson2RenderFactory;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Configuration
public class FastJsonConfig {
    @Bean
    public void jsonInit(@Inject Fastjson2RenderFactory factory, @Inject Fastjson2ActionExecutor executor){
        //示例1：通过转换器，做简单类型的定制
        factory.addConvertor(Date.class, s -> s.getTime());

        factory.addConvertor(LocalDate.class, s -> s.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

        factory.addConvertor(Long.class, s -> String.valueOf(s));

        factory.addConvertor(BigDecimal.class, s -> s.toPlainString());

        //示例2：通过编码器，做复杂类型的原生定制（基于框架原生接口）
        factory.addEncoder(Date.class, (out, obj, o1, type, i) -> {
            out.writeInt64(((Date) obj).getTime());
        });

        //示例3：重置序列化特性（例，添加序列化null的特性）
        factory.addFeatures(JSONWriter.Feature.WriteMapNullValue); //添加特性
        //factory.removeFeatures(JSONWriter.Feature.BrowserCompatible); //移除特性
        //factory.setFeatures(...); //重设特性


        //factory.config()...
        //executor.config()...
    }
}
